package thread;

/**
 * 多线程并发安全问题
 */
public class SyncDemo {
    public static void main(String[] args) {
        Table t1 = new Table();
        Thread jia = new Thread("甲"){
          public void run(){
              while(true){
                  int a = t1.getBeans();
                  //Thread.yield();
                  System.out.println(getName()+":"+a);
              }
          }
        };


        //Table t2 = new Table();
        Thread yi = new Thread("乙"){
            public void run(){
                while(true){
                    int a = t1.getBeans();
                    //Thread.yield();
                    System.out.println(getName()+":"+a);
                }
            }
        };


        jia.start();
        yi.start();
    }
}

class Table{
    private int beans = -1;//桌子上有20个豆子

    public  int getBeans(){//从座子上拿一个豆子
        if (beans==0){
            throw new RuntimeException("没有豆子了");
        }

        //使用主动放弃时间片来模拟线程执行到这没时间了
        //1
        Thread.yield();//让运行该方法的线程主动放弃本次剩余时间片
        return beans--;
    }
}
